using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Alidns20150109;
using AlibabaCloud.SDK.Alidns20150109.Models;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace UpdateAliDNS
{
    internal class Program
    {
        static Logger logger = LogManager.GetCurrentClassLogger();
        static async Task Main(string[] args)
        {
            try
            {
                var ip = (await GetPublicIP()).Trim();
                if (string.IsNullOrWhiteSpace(ip) || !IsIPAddress(ip))
                {
                    logger.Error("无法获取公网IP。");
                    return;
                }
                logger.Info($"当前IP：{ip}");

                var region = ConfigurationManager.AppSettings["region"];
                var key_id = ConfigurationManager.AppSettings["key_id"];
                var key_secret = ConfigurationManager.AppSettings["key_secret"];

                var domain = ConfigurationManager.AppSettings["domain"];
                var dns_rr = ConfigurationManager.AppSettings["dns_rr"];
                var dns_type = ConfigurationManager.AppSettings["dns_type"];

                var config = new Config();
                config.AccessKeyId = key_id;
                config.AccessKeySecret = key_secret;
                config.RegionId = region;
                var client = new Client(config);

                // 2、获取当前解析设置的IP地址
                var qry_req = new DescribeDomainRecordsRequest();
                qry_req.DomainName = domain;
                qry_req.RRKeyWord = dns_rr;
                qry_req.Type = dns_type;

                var resp = client.DescribeDomainRecords(qry_req);
                var record = resp.Body.DomainRecords.Record.FirstOrDefault();
                if (record == null)
                {
                    logger.Error($"cannot get dns settings：{domain}/rr:{dns_rr},type:{dns_type}");
                    return;
                }

                //3、判断IP是否一致
                var record_id = record.RecordId;
                var old_ip = record.Value;
                if (old_ip == ip)
                {
                    logger.Info("ip not changed.");
                    return;
                }

                // 4、更新DNS的IP地址
                var upd_req = new UpdateDomainRecordRequest();
                upd_req.RR = dns_rr;
                upd_req.Type = dns_type;
                upd_req.RecordId = record.RecordId;
                upd_req.Value = ip;
                var resp1 = client.UpdateDomainRecord(upd_req);
                logger.Info("update completed.");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            finally
            {
                logger.Info("exit.");
                logger.Info("====================");
            }
        }

        /// <summary>
        /// 获取公网IP地址
        /// </summary>
        /// <returns></returns>
        static async Task<string> GetPublicIP()
        {
            var qry_ip_url = "https://api.ipify.org";
            var ip = string.Empty;
            using (var client = new HttpClient())
            {
                try
                {
                    ip = await client.GetStringAsync(qry_ip_url);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                }
            }

            return ip;
        }

        static bool IsIPAddress(string ip)
        {
            var pattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
            return Regex.Match(ip, pattern).Success;
        }
    }
}
